//
//  CBVedioViewController.m
//  CultureBreath
//
//  Created by lanou on 15/10/24.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "CBVedioViewController.h"
#import "PKRequestManager.h"
#import "MJRefresh.h"
#import "CBVedioTopView.h"
#import "CBVedioListViewCell.h"
#import "CBVedioDetailViewController.h"
#import "Reachability.h"
#import "FMDatabase.h"
@interface CBVedioViewController () <UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UIScrollView *mainScrollView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) int day;
@property (nonatomic, strong) NSMutableDictionary *dataDic;
@property (nonatomic, strong) NSMutableArray *numArray;
@property (nonatomic, assign) NSInteger number;
@property (nonatomic, copy) NSString *monthString;
@property (nonatomic, copy) NSString *dayString;
@property (nonatomic, strong) Reachability *reach;

@property (nonatomic, strong) FMDatabase *dataBase; // 数据库持久化
@property (nonatomic, assign) int num;

@end

@implementation CBVedioViewController

-(NSMutableDictionary *)dataDic
{
    if (_dataDic == nil) {
        self.dataDic = [NSMutableDictionary dictionary];
    }
    return _dataDic;
}

-(NSMutableArray *)numArray
{
    if (_numArray == nil) {
        self.numArray = [NSMutableArray array];
    }
    return _numArray;
}

// 网络请求
- (void)configureData
{
    if (self.day <= 0) {
        self.monthString = [NSString stringWithFormat:@"%ld",[_monthString integerValue]];
    }
    NSDictionary *parDic = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"2015%@%d",self.monthString,self.day],@"date",@"2",@"num", nil];
    
    [PKRequestManager PKRequestManagerrequsetWithType:POST URLString:@"http://baobab.wandoujia.com/api/v1/feed" ParDIc:parDic finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        [_dataBase executeUpdate:@"delete from EYE"];
        [_dataBase executeUpdate:@"INSERT INTO EYE (data) VALUES (?)",data];
        if (_num == 0) {
            [self.dataDic removeAllObjects];
            [self.numArray removeAllObjects];
        }
        for (int i = 0; i < [dic[@"dailyList"] count]; i++) {
            NSMutableArray *array = [NSMutableArray array];
            for (NSDictionary *vedioDic in dic[@"dailyList"][i][@"videoList"]) {
                CBVedioModel *vedioModel = [[CBVedioModel alloc]init];
                [vedioModel setValuesForKeysWithDictionary:vedioDic];
                [array addObject:vedioModel];
            }
            _num++;
            [self.dataDic setValue:array forKey:[NSString stringWithFormat:@"%d",_num]];
            [self.numArray addObject:[NSString stringWithFormat:@"%d",_num]];
        }
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        [self.tableView reloadData];
    } error:^(NSError *error) {
        NSLog(@"%@",[error localizedDescription]);
    }];
}

// 判断有没有网络
-(void)reachabilityChanged:(NSNotification*)note
{
    Reachability * reach = [note object];
    NSParameterAssert([reach isKindOfClass: [Reachability class]]);
    NetworkStatus status = [reach currentReachabilityStatus];
    
    //    //用于检测是否是WIFI
    //    NSLog(@"%d",([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable));
    //    //用于检查是否是3G
    //    NSLog(@"%d",([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable));
    
    if (status == NotReachable) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"当前网络不可用,请检查您的网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertView show];
        NSLog(@"Notification Says Unreachable");
    }else if(status == ReachableViaWWAN){
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"您已连接移动网络,请考虑连接Wifi" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertView show];
    }else if(status == ReachableViaWiFi){
        
        //        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"您已连接WIfi网络,请放心使用" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        //        [alertView show];
        NSLog(@"连接上wifi");
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _num = 0;
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"MM"];
    NSDate *date = [[NSDate alloc]init];
    _monthString = [formatter stringFromDate:date];
    
    [formatter setDateFormat:@"dd"];
    _dayString = [formatter stringFromDate:date];
    _day = [_dayString intValue];
    
    CBVedioTopView *topView = [[CBVedioTopView alloc]initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, 50)];
    [topView.button addTarget:self action:@selector(getBackToRootViewController:) forControlEvents:UIControlEventTouchUpInside];
    [topView.eyeButton setImage:[UIImage imageNamed:@"eyeL"] forState:UIControlStateNormal];
    [topView.eyeButton addTarget:self action:@selector(getIntoCBVedioDetailViewController:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:topView];
    
    [self configureData];
    
    _mainScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 70, SCREEN_WIDTH, SCREEN_HEIGHT-70)];
    [self.view addSubview:_mainScrollView];

    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    self.tableView.rowHeight = SCREEN_HEIGHT/3;
    [self.tableView registerClass:[CBVedioListViewCell class] forCellReuseIdentifier:@"CBVedioListViewCell"];
    
    __weak CBVedioViewController *vedioVC = self;
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        vedioVC.day -= 2;
        [self configureData];
    }];
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _num = 0;
        vedioVC.day = [self.dayString intValue];
        [self configureData];
    }];
    [self.mainScrollView addSubview:_tableView];
    ///开启网络状况的监听
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    self.reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    [self.reach startNotifier]; //开始监听，会启动一个run loop
    
    
    // 创建一个database可以打开的文件 用来保存数据
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"Faner.db"];
    // 根据路径设置打开文件 不存在则创建这个文件
    _dataBase =  [FMDatabase databaseWithPath:filePath];
    NSLog(@"filePath = %@",filePath);
    // 通过open这个方法打开数据库 打开成功就返回YES 失败返回NO
    if ([_dataBase open]) {
        NSLog(@"数据库打开成功");
        [_dataBase executeUpdate:@"CREATE TABLE EYE (data blob)"];
    }else
    {
        NSLog(@"数据库打开失败");
    }
    
    // 根据查找语句查找表里面的内容
    FMResultSet *resultSet = [_dataBase executeQueryWithFormat:@"SELECT * FROM EYE"];
    // [resultSet next] 用到了类似C语言链表的东西 每一个对象都有一个属性保存了下一个对象的指针 可以通过while循环来获取所有我们想要得到的对象
    while ([resultSet next]) {
        
     NSData *data = [resultSet dataForColumn:@"data"];
     NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
     for (int i = 0; i < [dic[@"dailyList"] count]; i++) {
     NSMutableArray *array = [NSMutableArray array];
     for (NSDictionary *vedioDic in dic[@"dailyList"][i][@"videoList"]) {
     CBVedioModel *vedioModel = [[CBVedioModel alloc]init];
     [vedioModel setValuesForKeysWithDictionary:vedioDic];
     [array addObject:vedioModel];
     }
     [self.dataDic setValue:array forKey:[NSString stringWithFormat:@"%d",i]];
     [self.numArray addObject:[NSString stringWithFormat:@"%d",i]];
       }
    }
    [resultSet close];
    
}

// 查看处于中间的那个活动
- (void)getIntoCBVedioDetailViewController:(UIButton *)button
{
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"不支持" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alertView show];
}

- (void)getBackToRootViewController:(UIButton *)button
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.numArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self.dataDic[self.numArray[section]] count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CBVedioListViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CBVedioListViewCell" forIndexPath:indexPath];
    
    NSArray *array = self.dataDic[self.numArray[indexPath.section]];
    cell.vedioModel = (CBVedioModel *)array[indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CBVedioDetailViewController *vedioDetailVC = [[CBVedioDetailViewController alloc]init];
    
    vedioDetailVC.dataArray = self.dataDic[self.numArray[indexPath.section]];
    vedioDetailVC.index = indexPath.row;
    [self presentViewController:vedioDetailVC animated:YES completion:nil];
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return nil;
    }
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    if ([_dayString integerValue]- section > 0) {
        titleLabel.text = [NSString stringWithFormat:@"- %0.2ld.%0.2ld -",(long)[_monthString integerValue], [_dayString integerValue]-section];
    }
    if ([_dayString integerValue]- section <= 0) {
        _dayString = @"31";
        _monthString = [NSString stringWithFormat:@"%ld",[_monthString integerValue] - 1];
        titleLabel.text = [NSString stringWithFormat:@"- %0.2ld.%0.2ld -",(long)[_monthString integerValue], [_dayString integerValue]-section];
    }
    return titleLabel;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0.1;
    }else
    {
        return 30;
    }
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
